%%%-----------------------------------------------------------------------------
%%% @doc
%%% web phone ets
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(package_ets).

-behavior(gen_server).

-export([start_link/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-record(state, {tablename}).

%%------------------------------------------------------------------------------
%% @doc
%% Start web phone  ets.
%%
%% @end
%%------------------------------------------------------------------------------
start_link() ->
  gen_server2:start_link({local, ?MODULE}, ?MODULE, [], []).

%%%=============================================================================
%%% gen_server callbacks
%%%=============================================================================

init([]) ->
  process_flag(trap_exit, true),
  TableName = ets:new(package_ets, [public,named_table,duplicate_bag]),
  {ok, #state{tablename = TableName}}.

handle_call({find,Key},_From,State) ->
  Result = (
      try ets:lookup_element(State#state.tablename, Key, 2) of
        Value ->
          Value
      catch
        _:_ ->
          ""
      end
  ),
  {reply,Result,State};

handle_call(Request, _From, State) ->
  lager:error("unexpected request: ~p", [Request]),
  {stop, {error, unexpected_request}, State}.


handle_cast({delete, Key}, State) ->
  ets:delete(State#state.tablename, Key),
  {noreply, State};
  
handle_cast({insert,Key,Value}, State) ->
  ets:insert(State#state.tablename, {Key, Value}),
  {noreply, State};

handle_cast(Msg, State) ->
  lager:error("unexpected msg: ~p", [Msg]),
  {noreply, State}.

handle_info(Info, State) ->
  lager:error("unexpected info: ~p", [Info]),
  {noreply, State}.

terminate(_Reason, _State) ->
  ok.

code_change(_OldVsn, State, _Extra) ->
  {ok, State}.


